package com.turing.selfwebservice.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 该类定义了几个静态的Servlet常用方法，通过这几个方法，用户可以从输入的请求取出对应值、向用户返回 操作错误信息，并对一些输入信息进行格式转换
 */
public class ServletUtil {
	public static String dateFormat = "yyyy-MM-dd";
	public static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	public static DecimalFormat numf = new DecimalFormat();
	public static final String CURRENCY_FEN_REGEX = "\\-?[0-9]+";

	/**
	 * 获取字符串的长度，如果有中文，则每个中文字符计为2位
	 * 
	 * @param value
	 * @return
	 */
	public static int getStringLength(String value) {
		if (value == null || value.length() == 0) {
			return 0;
		}
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < value.length(); i++) {
			/* 获取一个字符 */
			String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
		}
		return valueLength;
	}

	/**
	 * 检查request.getParameter()返回值若为(空,"","null")则返回false
	 * 
	 * @param str
	 * @return
	 */
	public static boolean checkReuqestParameter(String str) {
		if (null == str || "".equals(str) || "null".equals(str)) {
			return false;
		}
		return true;
	}

	/**
	 * 将数据库中amount分转换为前台以"元"为单位
	 * 
	 * @param fen
	 * @return
	 */
	public static String changeF2Y(String amount) throws Exception {
		if (!amount.matches(CURRENCY_FEN_REGEX)) {
			throw new Exception("金额格式有误");
		}
		return BigDecimal.valueOf(Long.valueOf(amount)).divide(
				new BigDecimal(100)).toString();
	}

	/**
	 * 将前台输入的以元为单位的金额,转化成以分为单位
	 * 
	 * @param amount
	 * @return
	 */
	public static String changeY2F(String amount) {
		String currency = amount.replaceAll("\\$|\\￥|\\,", "");
		int index = currency.indexOf(".");
		int length = currency.length();
		Long amLong = 0l;
		if (index == -1) {
			amLong = Long.valueOf(currency + "00");
		} else if (length - index >= 3) {
			amLong = Long.valueOf((currency.substring(0, index + 3)).replace(
					".", ""));
		} else if (length - index == 2) {
			amLong = Long.valueOf((currency.substring(0, index + 2)).replace(
					".", "") + 0);
		} else {
			amLong = Long.valueOf((currency.substring(0, index + 1)).replace(
					".", "")
					+ "00");
		}
		return amLong.toString();
	}

	/**
	 * 根据参数date返回yyyy-MM-dd HH:mm:ss格式时间
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDateyyyyMMddHHmmss(Date date) {
		if (null == date) {
			return "";
		}
		return sdf.format(date);
	}

	/**
	 * 在一些具体的操作失败时，向用户返回提示信息
	 * 
	 * @param response
	 * @param msg
	 *            提示信息
	 * @throws IOException
	 */
	public static void popMessage(HttpServletResponse response, String msg)
			throws IOException {
		PrintWriter out = response.getWriter();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache,must-revalidate");
		out
				.println("<script language='JavaScript' type='text/JavaScript'>alert('"
						+ msg + "');return;</script>");
	}

	/**
	 * 通过对输入的javabean对象进行内省，以该对象中的每个属性的名称为键，从输入的请求中取出属性所对应的值
	 * 
	 * @param beanObj
	 *            要分析的对象
	 * @return Date
	 */
	public static Object getObjectFromRequest(HttpServletRequest request,
			Object beanObj) {
		String colName = "";
		// Object[] value = new Object[1];
		try {
			BeanInfo info = Introspector.getBeanInfo(beanObj.getClass());
			PropertyDescriptor[] props = info.getPropertyDescriptors();
			for (int i = 0; i < props.length; i++) {
				colName = props[i].getName(); // 属性名
				// colName = colName.toUpperCase();
				Class propertyType = props[i].getPropertyType(); // 属性类型
				String para = request.getParameter(colName.toLowerCase());
				if (para == null || para.length() == 0)
					continue;
				String value = para.trim();
				Method setMethod = props[i].getWriteMethod();
				// System.out.println("colName is : " + colName + " value is : "
				// + value + "  ");
				if (propertyType.equals(String.class)) {
					if (value == null) {
						value = "";
					}
					setMethod.invoke(beanObj, new Object[] { value });
					// setMethod.invoke(beanObj, new Object[] {new
					// String(value.getBytes("gb2312"),"ISO-8859-1")});
				} else if (propertyType.equals(int.class)) {
					if (value != null) {
						if (!value.equals("")) {
							setMethod.invoke(beanObj, new Object[] { Integer
									.valueOf(value) });
						}
					}
				} else if (propertyType.equals(double.class)) {
					if (value != null) {
						if (!value.equals("")) {
							setMethod.invoke(beanObj, new Object[] { Double
									.valueOf(value) });
						}
					}
				} else if (propertyType.equals(java.util.Date.class)) {
					if (value != null) {
						if (!value.equals("")) {
							setMethod.invoke(beanObj,
									new Object[] { getDateFromString(value) });
						}
					}
				}
			}
			return beanObj;
		} catch (Exception e) {
			System.out.println("ServeltUtil : " + e.toString());
			// System.out.println(colName);
			return beanObj;
		}
	}

	public static String strFormat(String strIn) {
		if (strIn == null || strIn.length() < 1)
			return null;
		StringBuffer buf = new StringBuffer(strIn);
		for (int i = 0; i < buf.length(); i++) {
			if (buf.charAt(i) == '"') {
				buf.insert(i, '\\');
				i++;
			}
		}
		return buf.toString();
	}

	/**
	 * 将日期型转换成指定格式的字符型数据
	 * 
	 * @param date
	 *            日期
	 * @return String
	 */
	public static String getStringFromDate(java.util.Date date) {
		String ret = "";

		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);

		try {
			ret = formatter.format(date);
		} catch (Exception e) {

		}
		return ret;
	}

	public static float divZero(int up, int down) {
		if (down == 0) {
			return 0l;
		} else {
			return up / (float) down;
		}

	}

	/**
	 * 将字符串转换成指定格式的日期型数据
	 * 
	 * @param str
	 *            字符串日期
	 * @return Date
	 */
	public static java.util.Date getDateFromString(String str) {
		if (str == null)
			return null;
		java.util.Date ret = new java.util.Date();

		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
		try {
			ret = formatter.parse(str);
		} catch (Exception e) {
			return null;
		}
		return ret;
	}

	public static java.util.Date getDateFromString1(String str) {
		if (str == null)
			return null;
		java.util.Date ret = new java.util.Date();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			ret = formatter.parse(str);
		} catch (Exception e) {
			return null;
		}
		return ret;
	}

	public static String formatfloat2(float value) {
		/*
		 * try{ numf = (DecimalFormat)NumberFormat.getPercentInstance();
		 * }catch(ClassCastException e) { System.err.println(e); }
		 */
		numf.applyPattern("0.00‰");
		if (value == 0)
			return "0";
		else
			return numf.format(value);
	}

	public static String formatfloatT3(float value) {
		/*
		 * try{ numf = (DecimalFormat)NumberFormat.getPercentInstance();
		 * }catch(ClassCastException e) { System.err.println(e); }
		 */
		numf.applyPattern("00.00‰");
		String val;

		if (value == 0)
			return "0";
		else {
			val = numf.format(value);
			val = val.substring(0, val.indexOf("‰"));
		}
		return val;
	}

	public static String formatfloatH(float value) {
		/*
		 * try{ numf = (DecimalFormat)NumberFormat.getPercentInstance();
		 * }catch(ClassCastException e) { System.err.println(e); }
		 */
		numf.applyPattern("00.00%");
		String val;
		if (value == 0)
			return "0";
		else {
			val = numf.format(value);
			val = val.substring(0, val.indexOf("%"));
		}
		return val;
	}

	public static String formatfloat(float value) {
		/*
		 * try{ numf = (DecimalFormat)NumberFormat.getPercentInstance();
		 * }catch(ClassCastException e) { System.err.println(e); }
		 */
		numf.applyPattern("00.0000%");
		if (value == 0)
			return "0";
		else
			return numf.format(value);
	}

	/**
	 * 对输入的字符串数据进行检查，如果该输入为null，或0.0、或0，则以空字符串代替 否则返回该输入
	 * 
	 * @param param
	 *            字符串
	 * @return String
	 */
	public static String checkOut(String param) {
		if (param == null || "null".equals(param) || "0.0".equals(param)
				|| "0".equals(param))
			return "";
		else
			return param;
	}

	public static String formatMoney(float money) {
		numf.applyPattern("#,###,###,##0.00");
		if (money == 0)
			return "0.00";
		else
			return numf.format(money);
	}

	public static String formatMoney(double money) {
		numf.applyPattern("#,###,###,##0.00");
		if (money == 0)
			return "0.00";
		else
			return numf.format(money);
	}

	/**
	 * 对输入的时间数据格式化为指定格式的字符串
	 * 
	 * @param param
	 *            时间
	 * @return 字符串时间值
	 */
	public static String checkOut(java.util.Date param) {
		if (param == null)
			return "";
		else
			return getStringFromDate(param);
	}

	/**
	 * 取系统的当前年份
	 * 
	 * @return 年份
	 */
	public static int getCurrentYear() {
		String date = getStringFromDate(new java.util.Date());
		String year = date.substring(0, 4);
		return Integer.parseInt(year);
	}

	/**
	 * 取系统的当前月份
	 * 
	 * @return月份
	 */
	public static int getCurrentMonth() {
		String date = getStringFromDate(new java.util.Date());
		String month = date.substring(5, 7);
		return Integer.parseInt(month);
	}

	public static void main(String[] args) {
		System.out.println(ServletUtil.getCurrentYear());
		System.out.println(ServletUtil.getCurrentMonth());
	}

	// 求每月的天数
	public static int getDayOfMonth(int year, int month) {
		int[] daysInMonth = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
				30, 31 }; // 平年每月日期。

		// 判断是否闰年

		if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {

			if (month == 2) {
				return 29;
			}
		}
		return daysInMonth[month - 1];
	}

	public static long getQuot(String time1, String time2) {
		long quot = 0;
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			System.out.println(time1);
			System.out.println(time2);
			Date date1 = ft.parse(time1);
			Date date2 = ft.parse(time2);
			quot = date1.getTime() - date2.getTime();
			quot = quot / 1000 / 60;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return quot;
	}

	public static double getRound(String str) {
		double sum = Double.parseDouble(str) * 100D;
		sum = Math.round(sum);
		sum /= 100D;
		System.out.println("\u56DB\u820D\u4E94\u5165\uFF1A" + sum);
		return sum;
	}

	public static String filtrate(String str) {
		String reStr = "";
		StringTokenizer st = new StringTokenizer(str, "|");
		String cond_1 = "3=1";
		String cond_2 = "3=2";
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			if (token.equals(cond_1))
				reStr = "\u4E2A\u4EBA\u94F6\u884C\u4E1A\u52A1";
			else if (token.equals(cond_2))
				reStr = "\u516C\u53F8\u94F6\u884C\u4E1A\u52A1";
		}
		return reStr;
	}

	public static String str_Comb(String str[]) {
		String reStr = "";
		for (int i = 0; i < str.length; i++)
			reStr = reStr + str[i] + "|";

		if (reStr.endsWith("|"))
			reStr = reStr.substring(0, reStr.length() - 1);
		return reStr;
	}

	public static String strComma(String name) {
		if (name.equals(""))
			return name;
		String comma = ",";
		StringTokenizer st = new StringTokenizer(name, "|");
		String val;
		for (val = ""; st.hasMoreTokens(); val = val + comma)
			val = val + st.nextToken();

		if (val.endsWith(comma))
			val = val.substring(0, val.length() - comma.length());
		return val;
	}

	public static String getAddDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date strdate = ServletUtil.getDateFromString(date);
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(strdate);
		gc.add(5, 1);
		String strDate = sdf.format(gc.getTime());
		strDate = strDate + " 00:00:00";
		return strDate;
	}

	public static String strDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date strdate = ServletUtil.getDateFromString(date);
		String strDate = sdf.format(strdate);
		return strDate;
	}

	public static String getStartDate(String date) {
		String strDate = date;
		strDate = strDate + " 00:00:00";
		return strDate;
	}

	public static String getEndDate(String date) {
		String strDate = date;
		strDate = strDate + " 23:59:59";
		return strDate;
	}

	public static String toISO_8859_1(String sGb) // 转码
	{
		if (sGb == null) {
			return null;
		}
		if (sGb.trim().length() == 0) {
			return sGb;
		}

		String sUnicode = "";
		try {
			sUnicode = new String(sGb.getBytes("GB2312"), "ISO-8859-1");
		} catch (Exception e) {
			return "";
		}
		return sUnicode;
	}

	public static String formatDate(String formatStr) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
		return dateFormat.format(new Date());
	}

	public static String transform(String content) {
		if (content == null)
			return "";
		content = content.replaceAll("&amp;", "&");
		content = content.replaceAll("&lt;", "<");
		content = content.replaceAll("&gt;", ">");
		content = content.replaceAll("&quot;", "\"");
		content = content.replaceAll("&#39;", "'");
		return content;
	}

	/**
	 * 判断字符串是否为空(NULL or length == 0)
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return (str == null || str.trim().length() == 0);
	}

}
